package com.base;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public abstract class BaseAdapter<DATA, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
    public Context mContext;
    ArrayList<DATA> dataList = new ArrayList();
    OnItemClickListener<DATA> onItemClickListener;
    HashMap<Integer, VH> holderMap = new HashMap();

    public interface OnItemClickListener<DATA> {
        void onItemClick(int position, DATA data);
    }

    public BaseAdapter(Context context) {
        mContext = context;
    }

    public BaseAdapter(Context context, OnItemClickListener<DATA> listener) {
        mContext = context;
        onItemClickListener = listener;
    }

    public void setData(DATA data) {
        if (data != null) {
            dataList.clear();
            dataList.add(data);
            notifyDataSetChanged();
        }
    }

    public void setData(ArrayList<DATA> dataList) {
        this.dataList.clear();
        if (dataList != null) {
            this.dataList.addAll(dataList);
        }

        notifyDataSetChanged();
    }

    public void delData(int position) {
        dataList.remove(position);
        notifyItemRemoved(position);


    }

    public void addData(DATA data) {
        if (dataList != null) {
            dataList.add(data);
            notifyItemChanged(dataList.size() - 1);
        }
    }

    public void addData(ArrayList<DATA> dataList) {
        if (dataList != null && dataList.size() > 0) {
            int sizeOld = 0;
            if (this.dataList.size() > 0) {
                sizeOld = this.dataList.size() - 1;
            }
            this.dataList.addAll(dataList);
            notifyItemChanged(this.dataList.size() - 1);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener(v -> {
                onItemClickListener.onItemClick(position, getItem(position));
            });
        }
        holderMap.put(position, holder);
        onBindView(holder, position, getItem(position));
    }

    public DATA getItem(int position) {

        if (position >= dataList.size()) {
            return null;
        } else {
            return dataList.get(position);
        }
    }

    public List<DATA> getDatas() {
        return dataList;
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    protected abstract void onBindView(VH holder, int position, DATA data);
}
